<script setup lang='ts'>

// 自定义 规则
interface FromInfo {
    all: Array<FromInfoItem>, //合作门店表单
    ing: Array<FromInfoItem>, //未合作门店表单
    not: Array<FromInfoItem>, //意向门店
    want: Array<FromInfoItem> //所有门店类型都需要填写表单
}
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
//const { } = defineProps<Props>();
import Box from './components/box.vue'
import Bottom from '@/components/bottom/index.vue';
import { useMarkerStore, useNotepadStore } from '@/store/index';
import { https } from '@/api/api';
import { showToast, upload, currentLocation } from '@/public';
const Map = require('../../public/amap/mapWx.js');
const cLngLat = ref('');
/**
 * @property 变量
 */
const fromInfo = ref<FromInfo>();
const notepadStore = useNotepadStore();
const markerStore = useMarkerStore();
const value = ref('')
const picList = ref<Array<Files>>([]);

const BoxRef = ref<Array<{ exposeChechedInfo: Function }>>();
const statusBottomHeight = computed(() => { return uni.getSystemInfoSync().safeAreaInsets?.bottom })
/**
 * @property  所有请求以api开头 如:apiDataInfo
 */
// 获取动态表单
const apiStoreFrom = async () => {
    const res = await https({
        mode: 'notepad',
        name: 'apiGetFollowUpForm'
    })
    if (res.code !== 0) return showToast(res.msg);
    fromInfo.value = res.data;
}
/**
 * @property 自定义事件 以事件名开头 如: clickButton,inputDev
 */
const clickSave = async () => {
    uni.showLoading({ title: '提交中' });
    try {
        const isTrue = BoxRef.value?.every(({ exposeChechedInfo }) => {
            const { info, type }: { info: CheckedInfo, type: number } = exposeChechedInfo();
            if (type === 2) {
                return Boolean(info.input)
            }
            if (type === 1) {
                const mengepickShow = info.mengepick.length > 0 && info.mengepick.some(item => Boolean(item.input))
                const pickShow = info.pick.length > 0
                const txtpickShow = info.txtpick.length > 0 && info.txtpick.some(item => Boolean(item.input))
                return mengepickShow || pickShow || txtpickShow
            }
        })
        if (!isTrue) return showToast('所有数据都是必填或必选项,请完善');
        // if (!value.value) return showToast('请填写记事内容');
        if (picList.value.length === 0) return showToast('请上传回访记录图片')
        let lotlng: LngLat = await currentLocation() as LngLat;
        await clickGetPosition();

        // 中和from 数据
        const from = BoxRef.value?.map(({ exposeChechedInfo }) => {
            const { info, type }: { info: CheckedInfo, type: number } = exposeChechedInfo();
            if (type == 2) {
                return {
                    subid: info.subid,
                    input: info.input
                }
            }
            if (type == 1) {
                const data = {
                    subid: info.subid,
                    pick: info.pick,
                    txtpick: info.txtpick,
                    mengepick: info.mengepick,
                }
                return data
            }
        })
        const promiseAll: any = [];
        picList.value.forEach(item => {
            promiseAll.push(upload(item, 'UploadFollowUpImg'));
        })
        const p = Promise.all(promiseAll);
        const fileRef = await p;
        const imgs = fileRef.map(item => item.file);
        const res = await https({
            mode: 'notepad',
            name: 'apiAddFollowUp',
            data: {
                content: value.value,
                imgs: JSON.stringify(imgs),
                mid: markerStore.marker.mid + '',
                form: JSON.stringify(from),
                clng: lotlng?.lng,
                clat: lotlng?.lat,
                ctoponym: cLngLat.value
            }
        })
        if (res.code !== 0) return showToast(res.data.msg);
        uni.hideLoading();
        navBack()
    } catch (error) {
        uni.hideLoading();
    }
   
}
const navBack = () => {
    notepadStore.apiNotepadRecord();
    uni.navigateBack();
}
const afterRead = (e: { file: Array<Files> }) => {
    picList.value = e.file
}

const deletePic = (e: { index: number }) => {
    // 通过下标进行删除
    picList.value = picList.value.filter((item, i) => i !== e.index)
}
// 超出限制大小
const oversize = () => {
    showToast('图片不可大于2M');
}
// 文本换行
const confirmNewline = () => {
    value.value += '\r\n'
}
// 获取他当前位置信息
const clickGetPosition = async (): Promise<LngLat> => {
    const { lat, lng } = await currentLocation() as LngLat;
    return new Promise(reslove => {
        Map.reverseGeocoder({
            location: {
                latitude: lat,
                longitude: lng,
            },
            get_poi: 1,
            success: (res: any) => {
                cLngLat.value = res.result.address
                reslove({ lat, lng });
            },
            fail: (error: { message: string }) => {
                cLngLat.value = error.message
                showToast(error.message)
                reslove({ lat, lng });
            },
            complete: () => {
                // uni.hideLoading();
            }
        })
    })
}
/**
 * @property 内置方法
 */
onLoad(() => {
    apiStoreFrom();
})

</script>
<template>
    <div class="w-[100vw] bg-[#f2f2f2] pl-3 pr-3">
        <up-navbar leftText="编辑记事本" :autoBack="true" placeholder>
        </up-navbar>
        <div class="c-red font-size-32 pt-3">
            注：以下所有数据均为必填项，请认真填写
        </div>
        <!-- 合作门店 -->
        <div v-if="markerStore.marker.showsize === '0'">
            <Box v-for="(item, i) in fromInfo?.ing" :key="i" :data="item" ref="BoxRef" />
        </div>

        <!-- 未合作门店 -->
        <div v-if="markerStore.marker.showsize === '1'">
            <Box v-for="(item, i) in fromInfo?.not" :key="i" :data="item" ref="BoxRef" />
        </div>
        <!-- 意向门店 -->
        <div v-if="markerStore.marker.showsize === '2'">
            <Box v-for="(item, i) in fromInfo?.want" :key="i" :data="item" ref="BoxRef" />
        </div>

        <!-- 所有类型都展示 -->
        <Box v-for="(item, i) in fromInfo?.all" :key="i" :data="item" ref="BoxRef" />
        <div class="w-[100%] b-rd-2 bg-[#fff] pl-3 pr-3 mt-3">
            <up-textarea v-model="value" placeholder="请输入记事内容" count :height="120" :border="'none'" confirmType="换行"
                @confirm="confirmNewline"></up-textarea>
            <up-form :labelStyle="{
                marginBottom: '20rpx'
            }">
                <up-form-item label="上传图片" labelPosition="top" labelWidth="200">
                    <up-upload :fileList="picList" @afterRead="afterRead" @delete="deletePic" name="pic" multiple
                        :maxCount="3" :maxSize="2097152" @oversize="oversize" capture="camera"></up-upload>
                </up-form-item>
            </up-form>
        </div>
        <div class="h-68 w-[100%] mt-3">
            <Bottom text="保存" @click="clickSave" />
        </div>
    </div>
    <div :style="{ height: statusBottomHeight + 'px' }">

    </div>
</template>
<style lang="scss" scoped></style>